import axios from 'axios'
import { Toast } from 'vant'
import { ServeApi } from '../utils/config'
import { loginStore } from '@/pinia/modules/login'

const axiosService = axios.create({
  baseURL: ServeApi,
  timeout: 6000,
  retryDelay: 100, // 再次请求间隔
  retry: 1, // 最大请求次数
  retryCount: 1 // 请求次数
})
// cookies缓存
// axiosService.defaults.withCredentials = true;
// axiosService.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
// 请求
axiosService.interceptors.request.use(beforeRequest, requestError)
// 响应
axiosService.interceptors.response.use(afterResponse, responseError)

// 请求处理
function beforeRequest (config) {
  const store = loginStore()
  if (store.loginData.accessToken) {
    config.headers.authorization = store.loginData.accessToken || ''
  }
  // config.headers.common.token = store.state.user.token || sessionStorage.getItem('token') || localStorage.getItem('token')||''

  return config
}
// 响应处理
function afterResponse (response) {
  if (response.data.code !== 0) {
    Toast(response.data.data || response.data.msg)
    return
  }
  return Promise.resolve(response.data)
}

// 请求错误
function requestError (error) {
  Promise.reject(error)
}
// 响应错误
function responseError (error) {
  console.log('远程连接错误', error.code)

  const config = error.config

  if (!config || !config.retry) return Promise.reject(error)
  config.retryCount = config.retryCount || 0
  if (config.retryCount >= config.retry) {
    // Reject with the error
    // window.location.reload();
    return Promise.reject(error)
  }
  // Increase the retry count
  config.retryCount += 1
  // Create new promise to handle exponential backoff
  setTimeout(() => {
    axiosService(config)
  }, config.retryDelay || 100)
}

export default axiosService
